import React, { Component } from 'react'
import { Toast } from 'antd-mobile';
import './index.scss'
import { API } from '../../utils/axios'
import { getCurrentCity } from '../../utils';
import { List, AutoSizer } from 'react-virtualized';
import NavHeader from '../../components/NavHeader'

// 格式化城市数据
const formatCityData = list => {
  let cityList = {};
  let cityIndex = [];

  list.forEach(item => {
    // 拿到每个城市的第一个字母
    const first = item.short[0];
    // 判断是否有该对象数组
    // 有则直接添加
    if (cityList[first]) cityList[first].push(item);
    // 没有则创建新数组然后添加
    else cityList[first] = [item];
  });
  // 获取索引数据,获取键，然后排序。
  cityIndex = Object.keys(cityList).sort();
  return { cityList, cityIndex };
}

// 标题索引高度
const TITLE_HEIGHT = 36;
// 每个曾城市的高度
const NAME_HEIGHT = 36;
// 城市名字
const CITY_NAME = ['北京', '上海', '广州', '深圳'];

// 格式化输出函数
const formatCityIndex = item => item = item === 'hot' ? '热门城市' : (item === '#') ? '当前定位' : item.toUpperCase();

export default class CityList extends Component {

  state = {
    cityList: {},
    cityIndex: [],
    // 指定高亮
    activeIndex: 0
  }

  async componentDidMount() {
    // await 加上await是进行异步等待，此时需要getCityList执行完毕才向下执行
    // 反制止 measureAllRows 调用时还没有数据
    // 开启加载提示
    Toast.loading('加载中...', 0, null, false);
    await this.getCityList();
    Toast.hide();
    // 调用 measureAllRows 方法提前计算list每行高度
    this.index.measureAllRows();
  }

  render() {
    return (
      <div className="citylist">
        {/* 顶部导航栏 */}
        <NavHeader>城市选择</NavHeader>
        {/* 城市列表项 */}
        <AutoSizer>
          {
            ({ width, height }) => <List
              style={{ scrollBehavior: 'smooth' }}
              ref={c => this.index = c}
              width={width}
              height={height}
              rowCount={this.state.cityIndex.length}
              rowHeight={this.getrowHeight}
              rowRenderer={this.rowRenderer}
              onRowsRendered={this.onRowsRendered}
              scrollToAlignment="start"
            />
          }
        </AutoSizer>
        {/* 索引列表 */}
        <ul className="city-index">
          {this.renderCityIndex()}
        </ul>
      </div>
    )
  }

  changeCity = ({ label, value }) => {
    return () => {
      if (CITY_NAME.indexOf(label) === -1) return Toast.info('暂无房源~(=´ω｀=)', 2, null, false);
      window.localStorage.setItem('hkzf_city', JSON.stringify({ label, value }));
      this.props.history.goBack();
    }
  }

  // 渲染函数 -----------------------------------
  // 渲染指向问题
  onRowsRendered = ({ startIndex }) => {
    // console.log(startIndex);
    if (this.state.activeIndex !== startIndex) this.setState({ activeIndex: startIndex });
  }

  // 渲染右侧索引列表
  renderCityIndex() {
    const { cityIndex, activeIndex } = this.state;
    return cityIndex.map((item, index) => (
      <li className="city-index-item" key={item} onClick={() => this.index.scrollToRow(index)}>
        <span className={activeIndex === index ? "index-active" : ''}>{item === 'hot' ? '热' : item.toUpperCase()}</span>
      </li>
    ));
  }

  // 渲染每一行的高度
  getrowHeight = ({ index }) => {
    const { cityIndex, cityList } = this.state;
    // 索引标题高度 + 城市数量 * 城市名称高度
    return TITLE_HEIGHT + cityList[cityIndex[index]].length * NAME_HEIGHT;
  }

  // 渲染列表
  rowRenderer = ({ key, index, isScrolling, isVisible, style }) => {
    const { cityIndex, cityList } = this.state;
    const letter = cityIndex[index];
    return (
      <div key={key} style={style} className="city">
        <div className="title">{formatCityIndex(letter)}</div>
        {
          cityList[letter].map(item => <div className="name" key={item.value} onClick={this.changeCity(item)}>{item.label}</div>)
        }
      </div>
    )
  }

  // 获取数据-----------------------------------------------
  // 获取城市数据
  async getCityList() {
    const { data } = await API.get('/area/city?level=1');
    const { cityList, cityIndex } = formatCityData(data.body);
    // console.log(cityList, cityIndex);

    /**
     * 获取热门城市
     */
    const hotCitys = await API.get('/area/hot');
    cityList['hot'] = hotCitys.data.body;
    cityIndex.unshift('hot');

    // 获取当前城市
    const currentCity = await getCurrentCity();
    //  console.log(cityList, cityIndex, currentCity);
    cityList['#'] = [currentCity];
    cityIndex.unshift('#');
    this.setState({ cityList, cityIndex });
  }
}
